<template>
  <section class="dg-art">

    <transition name="slide-down"><div v-show="toggle">

      <!-- 头像 -->
      <div class="am-g">
        <div class="am-u-sm-7 am-u-md-10 am-u-sm-centered" @click="changeHeadImgModal">
          <am-popover ref="upload-alt" placement="right">点击修改头像</am-popover>
          <am-image
            custom-class="am-margin-bottom-xs am-center"
            v-lazy="static_pic + imgPath"
            :responsive="true"
            :round="true"
            v-popover:upload-alt
            :src="''" />
          <!-- <upload-img
            :type="'headImg'"
            v-popover:upload-alt
            :autoUpload="true"
            :imgPath.sync="imgPath"
            :circle="true" /> -->
        </div>
      </div>

      <!-- 基本资料字段 -->
      <div class="am-container" v-if="isBasic">
        <am-list :static="true">
          <am-list-item v-for="(item, index) in showField" :key="index" v-if="item.key !== 'headImagePath'">
            <b>{{ item.name }}：</b>

            <template v-if="item.key === 'sex'">
              <am-radio-group v-model="sexName" >
                <am-radio label="男"></am-radio>
                <am-radio label="女"></am-radio>
              </am-radio-group>
            </template>

            <template v-else-if="item.key === 'introduction'">
              <textarea rows="5"
                :class="[ editing.index === index ? 'input-underline' : 'input-update']"
                v-model="item.value"
                @click="edit(item, index)"
                @blur="save(item)" />
            </template>

            <template v-else>
              <input
                :class="[ editing.index === index ? 'input-underline' : 'input-update']"
                v-model="item.value"
                @click="edit(item, index)"
                @blur="save(item)" />
            </template>
          </am-list-item>
        </am-list>
      </div>

      <!-- 门店资料字段 -->
      <!-- <div class="am-container" v-if="!isBasic">
        <am-list :static="true">
          <am-list-item v-for="(item, index) in v_field" :key="index" v-if="item.key !== 'storeMainPic'">
            <span>{{ item.name }}</span>：

            <template v-if="item.key === 'province'">
              <select class="am-form-field" v-model="province">
                <option v-for="(item, index) in provinces" :key="index"
                  :value="item.label">{{ item.label }}</option>
              </select>
            </template>

            <template v-else-if="item.key === 'city'">
              <select class="am-form-field" v-model="city">
                <option v-for="(item, index) in cities" :key="index"
                  :value="item.label">{{ item.label }}</option>
              </select>
            </template>

            <template v-else>
              <div v-if="editing.index !== index" @click="edit(item, index)">{{ item.value || 'null' }}</div>
              <input type="text" ref="input" class="input-underline" v-if="editing.index === index" v-model="item.value" @blur="save(item)" />
            </template>
          </am-list-item>
        </am-list>
      </div> -->

      <!-- 其他操作 -->
      <div class="am-container">
        <am-button custom-class="am-btn-block" @click="changePwdModal">修改密码</am-button>
        <!-- <am-button custom-class="am-btn-block am-text-truncate" v-if="isBasic" @click="toggleField" disabled>门店资料（后期）</am-button> -->
        <am-button custom-class="am-btn-block" v-if="!isBasic" @click="toggleField">基本资料</am-button>
      </div>
    
    </div></transition>

    <div class="am-comtainer dg-md-up-hide">
      <a href="javascript:;" class="am-link-muted am-center am-text-center am-margin-top"
        @click="toggle = !toggle">收起打开</a>
    </div>

    <!-- 修改密码模态框 -->
    <modal :modalVisible.sync="modalVisible" :width="modalWidth">
      <template v-if="pwdORimg">

        <div slot="header">修改密码</div>

        <am-form slot="body">
          <am-input-group :block="true">
            <am-input type="password" v-model="pwdChangeForm.oldPassword" placeholder="请输入旧密码"></am-input>
            <am-input-label slot="prepend" transparent>旧密码</am-input-label>
          </am-input-group>
          <am-input-group :block="true">
            <am-input type="password" v-model="pwdChangeForm.password" placeholder="请输入新密码"></am-input>
            <am-input-label slot="prepend" transparent>新密码</am-input-label>
          </am-input-group>
          <am-input-group :block="true">
            <am-input type="password" v-model="pwdChangeForm.rePassword" placeholder="请输入二次密码"></am-input>
            <am-input-label slot="prepend" transparent>确认密码</am-input-label>
          </am-input-group>
        </am-form>

        <p class="am-text-danger" v-if="!validator.oldPassword.vld">{{ validator.oldPassword.msg }}</p>
        <p class="am-text-danger" v-if="!validator.password.vld">{{ validator.password.msg }}</p>
        <p class="am-text-danger" v-if="!validator.rePassword.vld">{{ validator.rePassword.msg }}</p>

        <am-button slot="footer" color="primary" v-if="!submitAbled" disabled>确认修改（请填写所有密码）</am-button>
        <am-button slot="footer" color="primary" v-else @click="changePwd">确认修改</am-button>

      </template>

      <template v-else>
        <div slot="header">你的头像</div>
        <v-touch tag="div" slot="body" @pinchin="pinchin" @pinchout="pinchout" :pinchOptions="{threshold: 0.2}">
          <clip-upload-img
            ref="clip-img"
            :imgPath="imgPath"
            />
        </v-touch>

        <template slot="footer">
          <div class="am-form-group am-form-file am-inline-block am-fl" style="margin-top: 6px;margin-left: 8px;">
            <button type="button" class="am-btn am-btn-primary am-btn-sm">
              <i class="am-icon-cloud-upload"></i>选择头像</button>
            <input type="file" class="dg-file" accept="image/png, image/jpeg, image/jpg" @click="loading" @change="change($event)">
          </div>
          <button type="button" class="am-btn am-btn-primary am-btn-sm" @click="upload">确认</button>
        </template>
      </template>
    </modal>
  </section>
</template>

<script>
import UploadImg from '@/components/UploadImg'
import Modal from '@/components/Modal'
import regexUtil from 'regex-util'
import md5 from 'md5'
import ClipUploadImg from '@/components/ClipUploadImg'

export default {
  name: 'field-data',
  data() {
    return {
      loadingIns: {},
      modalWidth: 400,
      pwdORimg: true,// true改密码，false改头像
      designer: this.structure.GETADESIGNER(),// TODO字段响应式处理
      basicField: [// 设计师键、值、字段名称
      { key: 'name',
        value: '',
        name: '姓名'
      }, { key: 'sex',
        value: '1',
        name: '性别'
      }, { key: 'SvjiaNo',
        value: '',
        name: '三维家帐号'
      }, { key: 'tel',
        value: '',
        name: '手机'
      }, { key: 'email',
        value: '',
        name: '邮箱'
      }, { key: 'introduction',
        value: '',
        name: '自我介绍'
      }, { key: 'headImagePath',
        value: '',
        name: '头像'
      }],
      storeField: [// 店面师键、值、字段名称
      { key: 'storeName',
        value: '',
        name: '门店名称'
      }, { key: 'storeMainPic',
        value: '',
        name: '门头照'
      }, { key: 'storePic',
        value: '',
        name: '店面图'
      }, { key: 'province',
        value: '',
        name: '省'
      }, { key: 'city',
        value: '',
        name: '市、县'
      }, { key: 'address',
        value: '',
        name: '门店地址'
      }],
      showField: [],

      toggle: true,// 手机端收起打开

      temImgPath:　'',// 标记图片是否有修改过


      validator: {// 字段验证
        // true代表验证通过
        name: {
          msg: '名字不能为空'
        },
        tel: {
          msg: '手机格式不正确'
        },
        email: {
          msg: '邮箱格式不正确'
        },
        oldPassword: {
          vld: true,
          msg: '不能与旧密码相同'
        },
        password: {
          vld: true,
          msg: '6-12位大小写字母加数字组合，不得使用特殊字符'
        },
        rePassword: {
          vld: true,
          msg: '确认密码不一致'
        }
      },

      editing: {// 点击字段修改
        index:　-1,
        value: ''
      },
      imgPath: '',// 上传图片组件
      pwdChangeForm: {// 修改密码模态框表单
        oldPassword: '',
        password: '',
        rePassword: '',
      },
      headImgChangeForm: {

      },
      city: '',
      modalVisible: false,// 修改密码模态框



      /**
       * 属性非响应式使用
       */

      /**验证规则 */
      validate: {
        // 名称不为空
        'name': (val = '') => !!val,
        // 手机正则验证
        'tel': (val = '') => regexUtil.isPhone(val),
        // 邮箱正则验证
        'email': (val = '') => regexUtil.isEmail(val),
        // 旧密码验证
        'pwdChangeForm.oldPassword': (val = this.pwdChangeForm.oldPassword) => {
          if(this.pwdChangeForm.password !== '') {// 新密码不为空时，不能与新密码相同
            return this.validator.oldPassword.vld = (val !== this.pwdChangeForm.password);
          }
          return this.validator.oldPassword.vld = true;
        },
        // 新密码验证
        'pwdChangeForm.password': (val = this.pwdChangeForm.password) => {
          if(val !== '') {// 新密码不为空时，不能与旧密码相同，同时进行正则验证
            this.validator.oldPassword.vld = (val !== this.pwdChangeForm.oldPassword);
            return this.validator.password.vld = regexUtil.isPassword(val, true, false, 6, 12);
          }
          return this.validator.password.vld = true;
        },
        // 二次密码验证
        'pwdChangeForm.rePassword': (val = this.pwdChangeForm.rePassword) => {
          if(val !== '') {// 二次密码不为空时，一定要与新密码相同
            return this.validator.rePassword.vld = (this.pwdChangeForm.password === val ? true : false  )
          }
          return this.validator.rePassword.vld = true;
        }
      },


      pinchinTimer: false,
      pinchoutTimer: false,
      pinchinTO: {},
      pinchoutTO: {},


      /**
       * 后期
       */
      isBasic: true,// 基本资料，门店资料切换
      provinces: this.$store.state.provinces || [],// 静态省数据
    }
  },
  computed: {
    /**
     * vuex state
     */
    designerID() {
      return this.$store.state.designer.designerID
    },
    loginID() {
      return this.$store.state.designer.loginID;
    },
    screenWidth() {
      return this.$store.state.screenWidth;
    },


    /**修改密码的字段是否都填了 */
    submitAbled() {
      for(const field in this.pwdChangeForm) {
        if(this.pwdChangeForm[field] === '') {
          return false;
        }
      }
      return true;
    },

    /**
     * get field from designer
     * 普通字段使用v-model即可实现修改
     * 以下特殊字段需特殊处理
     */
    headImagePath: {// 头像
      get() {
        return this.basicField.find(field => field.key === 'headImagePath').value || '';
      },
      set(val) {
        this.basicField.find(field => field.key === 'headImagePath').value = val;
      }
    },
    storeMainPic: {// 店面图
      get() {
        return this.storeField.find(field => field.key === 'storeMainPic').value || '';
      },
      set(val) {
        this.storeField.find(field => field.key === 'storeMainPic').value = val;
      }
    },
    sexName: {// 性别名称
      get() {
        return this.basicField.find(field => field.key === 'sex').value === '1' ? '男' : '女';
      },
      set(val) {
        this.sex = (val === '男' ? '1' : '2');
      }
    },
    sex: {
      get() {
        return this.basicField.find(field => field.key === 'sex').value || '1';
      },
      set(val) {
        if(this.isBasic) {
          this.basicField.find(field => field.key === 'sex').value = val;
          this.updateField('sex', val);// TODO 上一行和上第十行都会触发一次update
        }
      }
    },

    /**
     * 后期
     */
    // province() {// 门店省
    //   return this.showfield.find(field => field.key === 'province').value || '';
    // },
    // cities() {// 市联动数据
    //   if(this.province) {
    //     return this.$store.getters.cities(this.province);
    //   } else {
    //     return [];
    //   }
    // },
  },
  components: {
    UploadImg, Modal, ClipUploadImg
  },
  methods: {
    ready() {
      this.co(function* () {
        yield this.loadData();
        // this.$store.commit('setDesignerJoin', this.designer.isJoin);// 参赛资格
        this.mergeField(this.designer);
        this.initShowField();
      });
    },
    loadData() {
      return this.loadDesigner();
    },

    loadDesigner() {
      return new Promise((resolve, reject) => {
        this.dgpost(this.api.GETDESIGNERBYID, {
          designerID: +this.designerID
        }).then(res => {
          this.designer = res.data.data;
          resolve();
        }).catch(err => {
          this.$message({
            title: '发生错误',
            message: '信息加载失败',
            type: 'warning',
            closeable: true
          });
          reject();
        });
      });
    },

    /**设计师数据分类，合并 */
    mergeField(designer) {
      this.basicField.forEach(field => {
        field.value = designer[field.key];
      });

      // this.storeField.forEach(field => {
      //   field.value = designer[field.key];
      // });
    },
    /**初始化要显示的数据 */
    initShowField() {
      this.showField = this.basicField || [];
    },

    /**编辑字段 */
    edit(item, index) {
      this.editing.index = index;
      this.editing.value = item.value;
    },
    /**保存字段 */
    save(item) {
      this.editing.index = -1;

      if(item.value !== this.editing.value) {// 更改了才操作
        const key = item.key;
        const newVal = item.value;
        const vldFun = this.validate[key];
        if(typeof vldFun === 'function') {// 该字段有验证器
          if(vldFun(newVal)) {
            this.updateField(key, newVal);
          } else {
            item.value = this.editing.value;
            this.$notify({
              message: this.validator[key].msg,
              type: 'warning'
            });
          }
        } else {// 没有验证器的直接过
          this.updateField(key, newVal);
        }

      }
    },

    /**显示修改密码模态框 */
    changePwdModal() {
      this.modalWidth = 400;
      this.pwdORimg = true;
      this.modalVisible = true;
    },
    /**改变头像，打开模态框 */
    changeHeadImgModal() {
      this.modalWidth = 600;
      this.pwdORimg = false;
      this.modalVisible = true;
    },


    /**
     * 头像处理函数
     * 移动端双指缩放
     */
    /**移动端模拟缩放，setTimeout性能优化 */
    pinchin() {
      if(!this.pinchinTimer) {
        window.clearTimeout(this.pinchoutTO);
        this.pinchinTimer = true;
        this.pinchinTO = setTimeout(() => {
          this.$refs['clip-img'].$refs['cropper'].changeScale(-0.5);
          this.pinchinTimer = false;
        }, 99);
      }
    },
    pinchout() {
      if(!this.pinchoutTimer) {
        window.clearTimeout(this.pinchinTO);
        this.pinchoutTimer = true;
        this.pinchoutTO = setTimeout(() => {
          this.$refs['clip-img'].$refs['cropper'].changeScale(0.5);
          this.pinchoutTimer = false;
        }, 99);
      }
    },
    loading() {
      this.loadingIns = this.$loading({ loadingText: '正在处理' });
    },


    /**选择头像 */
    change(event) {     

      /**ie兼容处理 */
      event = event || window.event
      const target = event.target || event.srcElement

      const file = target.files[0];
      const reader = new FileReader();
      reader.onload = e => {
        e = e || e.event;
        const target = e.target || e.srcElement;
        const data = target.result;
        this.$refs['clip-img'].option.img = data;
        setTimeout(() => this.loadingIns.close(), 599);
      }
      // reader.readAsArrayBuffer(file);// 转为Blob
      reader.readAsDataURL(file);// 转为base64     
    },
    /**确认上传 */
    async upload() {
      this.loadingIns = this.$loading({ loadingText: '正在上传' });
      const blob = await this.$refs['clip-img'].getCropBlob();
      const param = new FormData()  // 创建form对象

      /**fields */
      param.append('did', this.loginID);// 通过append向form对象添加数据
      param.append('name', 'image');
      param.append('type', 'headImg');
			param.append('image', blob, Math.random().toString(36).substr(5) + '.jpg');

			this.$http.post(this.api.UPLOADIMG, param, {
				headers: {'content-type': 'multipart/form-data'}
			}).then(res => {
        if(res.status === 200) {
          this.imgPath = res.data.data.path;
        }
        this.modalVisible = false;
        this.loadingIns.close();
			});
    },



    /**update字段 */
    updateField(key, value) {// TODO
      const sql = `update Svjia_designer set ${ key } = '${ value }' where id = '${ this.designerID }'`;
      console.log(sql);
      this.dgpost(this.api.UPDATESQL, {
        ls_sql: sql
      });
    },


    /**进行密码修改 */
    changePwd() {
      const delay = 399;

      this.dgpost(this.api.CHANGEPWD, {
        designerID: this.designerID,
        oldPassword: md5(this.pwdChangeForm.oldPassword),
        newPassword: md5(this.pwdChangeForm.password)
      }).then(() => {
        this.$notify({
          message: '修改成功，自动返回重新登录',
          type: 'success',
          delay
        });

        setTimeout(() => {
          this.modalVisible = false;
        }, (delay * 2));

        setTimeout(() => {
          this.$router.push('/');
        }, (delay * 3));
      }).catch(err => {
        this.pwdChangeForm.oldPassword = '';
        this.pwdChangeForm.password = '';
        this.pwdChangeForm.rePassword = '';
        this.$message({
          title: '修改密码发生错误',
          type: 'error',
          message: err.msg,
          closeable: true
        });
      });
    },


    /**
     * 后期
     */
    /**切换显示资料 */
    toggleField() {
      alert('后期功能，请到报名页填写门店资料');
      // this.isBasic = !this.isBasic;
      // this.v_field = this.isBasic ? this.v_basicField : this.v_storeField;
      // this.imgPath = this.isBasic ? this.headImagePath : this.storeMainPic;
      // this.temImgPath = this.imgPath;
    }
  },
  watch: {
    /**
     * 修改密码：输入同时验证
     */
    'pwdChangeForm.oldPassword': function(val) {
      this.validate['pwdChangeForm.password']();
      this.validate['pwdChangeForm.rePassword']();
    },
    'pwdChangeForm.password': function(val) {
      this.validate['pwdChangeForm.password'](val);
      this.validate['pwdChangeForm.rePassword'](this.pwdChangeForm.rePassword);
    },
    'pwdChangeForm.rePassword': function(val) {
      this.validate['pwdChangeForm.rePassword'](val);
      this.validate['pwdChangeForm.password'](this.pwdChangeForm.password);
    },



    /**
     * 当computed获得值，赋值
     * imgPath监测
     */
    headImagePath(val) {
      if(this.isBasic) {
        this.imgPath = val;
        this.temImgPath = this.imgPath;
      }
    },
    storeMainPic(val) {
      if(!this.isBasic) {
        this.imgPath = val;
        this.temImgPath = this.imgPath;
      }
    },


    /**上传完就直接修改 */
    imgPath(val) {
      const key = this.isBasic ? 'headImagePath' : 'storeMainPic';

      if(val !== this.temImgPath) {

        Promise.resolve()
        .then(() => {
          this.updateField(key, val);
        }).then(() => {
          if(this.isBasic) {
            this.headImagePath = val;
          } else {
            this.storeMainPic = val;
          }
        });
      }
    },

    screenWidth(val) {
      if(val > 640) {
        this.toggle = true;
      }
    }
  },
  mounted() {
    this.ready();
  }
}
</script>

<style scoped>
.input-update { cursor: pointer; border: none; width: 100%; }
.dg-file { position: absolute; left: 0; top: 0; z-index: 1; width: 100%; opacity: 0; cursor: pointer; font-size: 50rem; }
</style>